﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Reactor.Client.Messages;
using Reactor.Client.Services;

namespace Reactor.Client.ViewModel
{
    public class HomeViewModel : ViewModelBase
    {
        #region Fields

        private readonly IReactorServiceAgent _reactorServiceAgent;
        private readonly IMessenger _messenger;
        private ObservableCollection<CoreViewModel> _cores;
        private CoreViewModel _selectedCore;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="HomeViewModel"/> class.
        /// </summary>
        /// <param name="reactorServiceAgent">The reactor service agent.</param>
        /// <param name="messenger">The messenger.</param>
        public HomeViewModel(IReactorServiceAgent reactorServiceAgent, IMessenger messenger)
        {
            if (reactorServiceAgent == null) throw new ArgumentNullException("reactorServiceAgent");
            if (messenger == null) throw new ArgumentNullException("messenger");

            _reactorServiceAgent = reactorServiceAgent;
            _messenger = messenger;

            messenger.Register<CoreSelectedEvent>(this, e => { SelectedCore = e.CoreViewModel; });
        }

        public ObservableCollection<CoreViewModel> Cores
        {
            get
            {
                if (_cores == null)
                    _reactorServiceAgent.GetAllReactorCores(LoadCores);

                return _cores;
            }
        }

        public CoreViewModel SelectedCore
        {
            get { return _selectedCore; }
            set
            {
                if (value == _selectedCore) return;

                _selectedCore = value;
                RaisePropertyChanged("SelectedCore");
            }
        }

        public object CoreBackgroundImage
        {
            get
            {
                return new BitmapImage(new Uri(Application.Current.Host.Source, "../Images/Radioactive-32X32.png"));
            }
        }

        private void LoadCores(IEnumerable<CoreViewModel> cores)
        {
            _cores = new ObservableCollection<CoreViewModel>(cores);
            RaisePropertyChanged("Cores");
        }
    }
}
